//
//  LRXBuyThingController.m
//  路人侠
//
//  Created by zhangxulong on 3/12/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXBuyThingController.h"
#import "LRXThingMainScrollView.h"
#import "LRXThing.h"
#import "LRXThingRemaindView.h"
#import "LRXBuyPlaceModel.h"
#import "LRXBuyThingCell.h"
#import "LRXSubThingView.h"
#import "AppDelegate.h"
#import "LRXSeacheThingController.h"
#import "LRXLMeController.h"

@interface LRXBuyThingController()<
    UIScrollViewDelegate,
    ThingMainScrollViewDelegate,
    LRXThingRemaindViewDelegate,
    UITextFieldDelegate,
    SubThingViewDelegate
>

@property (nonatomic,strong) UIButton* snackBtn;
@property (nonatomic,strong) UIButton * foodBtn;
@property (nonatomic,strong) UIButton * articleBtn;
@property (nonatomic,strong) UIView * spot;
@property (nonatomic,strong) UIDynamicAnimator * animator;
@property (nonatomic,strong) LRXThingMainScrollView * mainScroll;
@property (nonatomic,strong) LRXThingRemaindView * thingRemind;
@property (nonatomic,strong) NSMutableArray * places;
@property (nonatomic,strong) NSMutableArray * placesBtns;
@property (nonatomic,assign) NSInteger page;
@end

static BOOL reloadDataBool;
@implementation LRXBuyThingController


- (void)viewDidLoad{
    
    self.view.backgroundColor = mainColor;
    self.navigationItem.title = @"路人侠商店";
    self.animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
    
    reloadDataBool = false;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(rightRightSearchClick:)];
    
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    //请求头部的数据  只是个开始
    [self loadSchoolPlaces];
    
}
- (void)rightRightSearchClick:(UIButton *)btn
{
    
    [self.navigationController pushViewController:[LRXSeacheThingController new] animated:YES];
    
}
+(void)setReLoadDataBool:(BOOL)reBool{
   
    
    reloadDataBool = reBool;
    
}
+(BOOL)getReloadDataBool{
    
    return reloadDataBool;
    
}


- (void)popViewController
{
    [self.navigationController popViewControllerAnimated:YES];
}

//头部视图的布局
- (void)loadSchoolPlaces
{
    
    [MBProgressHUD showMessage:@"加载中..." toView:[UIApplication sharedApplication].keyWindow];
    
    NSMutableArray * places = [NSMutableArray array];
    NSDictionary * param = @{@"s":@"1"};    //请求学校购买地点
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    manger.requestSerializer.timeoutInterval = 2;
    [manger GET:getNavUrl parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
            
            NSInteger  stateCode = [responseObject[@"data"][@"status_code"] integerValue];
            if (stateCode == 1) {
                for (NSDictionary * dic in responseObject[@"data"][@"dataset"]) {
                    LRXBuyPlaceModel * placeModel = [LRXBuyPlaceModel buyPlaceWith:dic];
                    [places addObject:placeModel];
                }
                self.places = places;
                [self layoutPlaceHead];
            }
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
        [MBProgressHUD showError:@"网络错误"];
    }];
}
//获取完学校的数据后 界面更新地点
- (void)layoutPlaceHead
{
    CGFloat snackBtnY = 50 * hScale;
    CGFloat snackBtnX = MainScreenW / (self.places.count + 1);
    NSMutableArray * placeBtns = [NSMutableArray array];
    for(int i = 0; i < self.places.count; i++)
    {
        LRXBuyPlaceModel * model = self.places[i];
        UIButton * snackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [snackBtn setTitle:model.placeName forState:UIControlStateNormal];
        snackBtn.titleLabel.font = [UIFont systemFontOfSize:28 * hScale];
        [snackBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [snackBtn setTitleColor:[UIColor colorWithRed:181 green:208 blue:252] forState:UIControlStateNormal];
        [snackBtn sizeToFit];
        
        snackBtn.center = CGPointMake((i+1) * snackBtnX, snackBtnY);
        snackBtn.tag = i;
        [snackBtn addTarget:self action:@selector(changBuyThingView:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:snackBtn];
        [placeBtns addObject:snackBtn];
        
        if (i == 0) {
            snackBtn.selected = YES;
        }
    }
    self.placesBtns = placeBtns;
    if (self.places.count > 0) {
        UIView * spot = [[UIView alloc]init];
        spot.backgroundColor = [UIColor colorWithRed:239 green:211 blue:24];
        CGFloat spotX = snackBtnX - 5 * hScale;
        CGFloat spotY = snackBtnY + 25 * hScale;
        spot.frame = CGRectMake(spotX, spotY, 10 * hScale, 10 * hScale);
        spot.layer.cornerRadius = 5 * hScale;
        self.spot = spot;
        
        [self.view addSubview:spot];
    }
    //布局购买地方内容视图
    [self layoutContentView];
    
}

//按钮的点击实现画面的滑动
- (void)changBuyThingView:(UIButton *)btn
{
    [UIView animateWithDuration:0.5 animations:^{
        self.mainScroll.contentOffset = CGPointMake(btn.tag * self.mainScroll.frame.size.width, 0);
    }];
 
}

//设置了购买的地方
- (void)layoutContentView
{
    //设计左右滑动的界面
    CGFloat mainScrollY = CGRectGetMaxY(self.spot.frame) + 7 * hScale;
    LRXThingMainScrollView * mainScroll = [[LRXThingMainScrollView alloc]init];
    mainScroll.showsHorizontalScrollIndicator = NO;
    mainScroll.delegate = self;
    mainScroll.thingMainDelegate = self;
    mainScroll.backgroundColor = [UIColor whiteColor];
    mainScroll.frame = CGRectMake(0, mainScrollY, self.view.frame.size.width, self.view.frame.size.height - mainScrollY);
    mainScroll.pagingEnabled = YES;
    mainScroll.contentSize = CGSizeMake(self.view.frame.size.width * self.places.count, mainScroll.frame.size.height);
    mainScroll.superController = self;
    self.mainScroll = mainScroll;
    [mainScroll layoutSubTableView:self.places];
    
    //物品提示栏
    LRXThingRemaindView * thingRemind = [[LRXThingRemaindView alloc]init];
    thingRemind.alpha = 0.7;
    thingRemind.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100 * wScale);
    thingRemind.thingRemaindDelegate = self;
    [thingRemind thingRemaindView];
    
    AppDelegate * appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    CGPoint point = CGPointMake(thingRemind.thingRemindLabel.frame.origin.x + thingRemind.thingRemindLabel.frame.size.width, thingRemind.thingRemindLabel.frame.origin.y - thingRemind.thingRemindLabel.frame.size.height );
    appdelegate.pointerCenter = [thingRemind convertPoint:point toView:[UIApplication sharedApplication].keyWindow];
    self.thingRemind = thingRemind;
    
    

    
    if ([LRXLMeController getSaveThingOfZero]!=nil) {
        
        [[LRXLMeController getSaveThingOfZero] removeAllObjects];
    
    }
    //更新提示View 的数据
    NSInteger reFlag = 0;
    if (![LRXBuyThingController getReloadDataBool]) {
        if ([LRXLMeController getBuy]!=nil) {
            
            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
            arr =  [LRXLMeController getBuy];
            
            [LRXBuyThingCell setBuyThing:arr];
            [LRXBuyThingCell setSelectedArray:arr];
            reFlag = 1;
            
        }
    }
    
    
    for (LRXThing *thing in [LRXBuyThingCell getSelectedArray]) {
        
        if (thing.reChonoseAddCount!=0) {
            NSInteger re = [thing.thingCount integerValue];
            re -= thing.reChonoseAddCount;
            thing.thingCount = [NSString stringWithFormat:@"%ld",re];
            thing.reChonoseAddCount=0;
        }
        if (thing.reChonoseSubCount!=0) {
            
            NSInteger re = [thing.thingCount integerValue];
            re += thing.reChonoseSubCount;
            thing.thingCount = [NSString stringWithFormat:@"%ld",(long)re];
            thing.reChonoseSubCount=0;
            
        }
    }
    
    
    if (reFlag==0) {
        NSMutableArray *array = [LRXBuyThingCell getBuyThing];
        [LRXBuyThingCell setConfirmbuyArray:array];
        
    }
    
    //显示showThingRemind
    [self updateThingRemind:[LRXBuyThingCell getSelectedArray]];
    [self showThingRemind];
    [self.view addSubview:self.mainScroll];
    [self.view addSubview:self.thingRemind];
    
}

//左右滑动 界面滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x / self.view.frame.size.width + 0.5;
    self.page = page;
    
    CGPoint durPoint = self.spot.center;
    for (int i = 0; i < self.placesBtns.count; i++) {
        UIButton * btn =  self.placesBtns[i];
        btn.selected = NO;
        if (page == i) {
            btn.selected = YES;
            durPoint= CGPointMake(btn.center.x, CGRectGetMaxY(btn.frame));
        }
    }
    //捕捉行为
    [self.animator removeAllBehaviors];
    //取出用户点击的点
    CGPoint point = durPoint;
    //创建一个捕捉行为
    UISnapBehavior * snap = [[UISnapBehavior alloc]initWithItem:self.spot snapToPoint:point];
    //设置捕捉行为的阻力
    snap.damping = 1;
    //在仿真器中 只能存在一个捕捉仿真行为
    [self.animator addBehavior:snap];
    [self.view endEditing:YES];
}

#pragma mark - thingRemaindDelegate提示框的view代理方法
- (void)accpetBtnClick
{

    if ([LRXLMeController getSaveThingOfZero]!=nil) {
        [[LRXLMeController getSaveThingOfZero] removeAllObjects];
    }
    
    for (LRXThing *thing in [LRXBuyThingCell getBuyThing]) {
        thing.reChonoseAddCount = 0;
        thing.reChonoseSubCount = 0;
    }
    
    _buyThings = [NSArray arrayWithArray:(NSArray *)[LRXBuyThingCell getSelectedArray]];
    
    [LRXBuyThingCell setBuyThing:_buyThings];
    
    if ([self.buyThingDelegate respondsToSelector:@selector(popThingView:)])
    {
        //[self.buyThingDelegate popThingView:[LRXBuyThingCell getBuyThing]];
    }
    
    //推出控制器
    [self popViewController];
    
    
}

- (void)subTableViewScroll
{
    [self.view endEditing:YES];
}

#pragma mark - LRXBuyThingCell 的更新thingRemaind 的代理方法
- (void)updateThingRemind:(NSArray *)thingArray
{
    
    NSInteger sumThingCount = 0;
    CGFloat sumThingMoney = 0;
    for (LRXThing * thing in thingArray) {
        sumThingCount += [thing.thingCount integerValue];
        sumThingMoney += ([thing.thingCount integerValue] * [thing.thingMoney floatValue]);
    }
    self.thingRemind.thingRemindMoney.text = [NSString stringWithFormat:@"共%.2lf元",sumThingMoney];
    self.thingRemind.thingRemindLabel.text = [NSString stringWithFormat:@"%ld",(long)sumThingCount];
    
}

- (void)showThingRemind
{
    
    [UIView animateWithDuration:0.2 animations:^{
        self.thingRemind.frame = CGRectMake(0, self.view.frame.size.height - 100 * hScale, self.view.frame.size.width, 100 * hScale);
    }];
    
}
- (void)hideThingRemind
{
    [UIView animateWithDuration:0.2 animations:^{
        self.thingRemind.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100 * hScale);
    }];
}

#pragma mark - LRXSubThingDelegate
- (void)storeCellClickToChangedTitle:(NSString *)title
{
    self.navigationItem.title = title;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self updateThingRemind:[LRXBuyThingCell getSelectedArray]];
    [self showThingRemind];
    
}

-(void)viewDidDisappear:(BOOL)animated{
    [self hideThingRemind];
}


@end
